package com.ourhours.message.service.impl;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.ourhours.message.domain.EmailSend;
import com.ourhours.message.domain.Supplier;
import com.ourhours.message.dto.EmailDto;
import com.ourhours.message.enums.MessageTypeEnum;
import com.ourhours.message.enums.SupplierTypeEnum;
import com.ourhours.message.exception.MessageException;
import com.ourhours.message.mapper.EmailSendMapper;
import com.ourhours.message.rpc.reference.emailapache.EmailApacheRpc;
import com.ourhours.message.service.EmailSendService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ourhours.message.service.SupplierService;
import com.ourhours.message.service.wrapper.SupplierWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * 邮件发送记录表 服务实现类
 * </p>
 *
 * @author chi.chen
 * @since 2018-03-21
 */
@Service
public class EmailSendServiceImpl extends ServiceImpl<EmailSendMapper, EmailSend> implements EmailSendService {

    private static final Logger LOGGER = LoggerFactory.getLogger(EmailSendServiceImpl.class);

    @Autowired
    SupplierService supplierService;

    @Autowired
    SupplierWrapper supplierWrapper;

    @Autowired
    EmailApacheRpc emailApacheRpc;

    public void sendEmail(EmailDto dto) {
        try {
            if (dto == null || dto.getVendorId() == null) {
                throw new MessageException("vendorId不能为空！");
            }
            Supplier entity = supplierWrapper.findSupplierWithCache(dto.getVendorId(), MessageTypeEnum.EMAIL.getCode());
            if (entity == null || entity.getId() == null) {
                throw new MessageException("根据vendorId=" + dto.getVendorId() + ",查询邮件发送供应商表数据为空！");
            }
            switch (SupplierTypeEnum.fromCode(entity.getSupplierType())) {
                case EMAIL_APACHE:
                    JSONObject jsonObject = JSONObject.parseObject(entity.getOuterExtraProperty());
                    String sourceName = jsonObject.getString("sourceName");
                    String sourceServer = jsonObject.getString("sourceServer");
                    emailApacheRpc.sendEmail(StringUtils.split(dto.getToAddresses(), ','), dto.getTitle(), dto.getContent(), entity.getOuterAppKey(), entity.getOuterSecret()
                            , sourceServer, sourceName, null, StringUtils.split(dto.getAttachmentUrls(), ','));
                    LOGGER.info("==>EmailSendService.sendEmail 发送邮件成功：参数:vendorId={},toAddress={},title={},content={},networkAttachment={}"
                            , dto.getVendorId(), dto.getToAddresses(), dto.getTitle(), dto.getContent(), dto.getAttachmentUrls());
            }
        } catch (Exception e) {
            LOGGER.error("==>EmailSendService.sendEmail 发送邮件失败：参数:vendorId={},toAddress={},title={},content={},networkAttachment={}, 结果:{}"
                    , dto.getVendorId(), dto.getToAddresses(), dto.getTitle(), dto.getContent(), dto.getAttachmentUrls(), e);
            throw e;
        }
    }

    public void setEmailSendStatus(Long id, Integer status, String errCode, String reason) {
        try {
            EmailSend entity = new EmailSend();
            entity.setId(id);
            entity.setStatus(status);
            if (status == -1) {
                entity.setFailureReason(errCode);
                entity.setFailureReason(reason);
            }
            entity.setUpdateTime(new Date());
            entity.setUpdateUser("MQ");
            this.updateById(entity);
        } catch (Exception e) {
            LOGGER.error("==>EmailSendService.setEmailSendStatus 保存记录状态失败，但不处理异常，参数:{},{},{},{},原因:{}", id, status, errCode, reason, e);
        }
    }
}
